package com.atguigu.cas;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

public class CASDemo
{

    private int number;

    public int getNumber()
    {
        return number;
    }

    public synchronized void setNumber()
    {
        ++number;
    }

    AtomicInteger atomicInteger = new AtomicInteger();

    public AtomicInteger getAtomicInteger()
    {
        return atomicInteger;
    }

    public void setAtomicInteger()
    {

        atomicInteger.getAndIncrement();

        atomicInteger.incrementAndGet();
    }

    public static void main(String[] args) throws InterruptedException
    {
        CASDemo casDemo = new CASDemo();
        CountDownLatch countDownLatch = new CountDownLatch(100);
        for (int i = 1; i <=100; i++) {
            new Thread(() -> {
                for (int j = 1; j <= 100; j++) {
                    casDemo.setNumber();
                    casDemo.setAtomicInteger();
                }
                countDownLatch.countDown();
            },String.valueOf(i)).start();
        }

        countDownLatch.await();
        System.out.println(Thread.currentThread().getName()+"获得最后结果： "+casDemo.getNumber());
        System.out.println(Thread.currentThread().getName()+"获得最后结果： "+casDemo.getAtomicInteger().get());

    }
}
